import { ReportClass, IndividualClass } from './report-constant.js';


const CLASS_OPTION = (function () {
    let list = [];
    list.push("<option value=\"\">请选择</option>");
    for (let i in IndividualClass){
        list.push("<option value=\"{value}\">{name}</option>".format(IndividualClass[i]))
    }
    return list.join('');
})();
const REPORT_OPTION = (function () {
    let list = [];
    list.push("<option value=\"\">请选择</option>");
    for (let i in ReportClass){
        list.push("<option value=\"{value}\">{name}</option>".format(ReportClass[i]))
    }
    return list.join('');
})();


$(function () {
    layui.use(['upload', 'jquery', 'form', 'layer', 'table', 'laytpl'], function() {
        var $ = layui.jquery, upload = layui.upload, form = layui.form, layer = layui.layer, table = layui.table, laytpl = layui.laytpl;

        //文件列表行模板
        const FILE_TABLE_ROW_TEMPLATE = $("#template-upload-row")[0].innerHTML;

        var File = function(file){
            //文件句柄
            this.file = file;
            // console.log('new File', file);
            //唯一索引
            let timestamp = file.lastModified;
            File.Index[timestamp] = File.Index[timestamp] ? ++File.Index[timestamp]: 1;
            this.index = timestamp.toString() + '-' + File.Index[timestamp];
            // console.log(this.index);
            //添加行UI
            this. tr = ( () => {
                //添加
                // console.log('tr-this', this);
                let index = this.index;
                let tr = $(laytpl(FILE_TABLE_ROW_TEMPLATE).render({
                    index: index,
                    name: this.file.name,
                    size: (this.file.size >> 10) + 'kb',
                    //status: '等待上传',
                    reportOption: REPORT_OPTION,
                    classOption: CLASS_OPTION,
                }));

                //重新选择
                tr.find('.action-select').on('click', (e) => {
                    e.stopPropagation();
                   $('#input-upload').data('reselect', this).removeAttr('multiple').click();
                });

                //删除
                tr.find('.action-delete').on('click', () => {
                    File.remove(this)
                }).removeClass('layui-hide'); //显示该按钮

                //显示错误信息
                tr.find('.action-displayError').on('click', () => {
                    if(this.showErrorMsg){this.showErrorMsg();}
                });

                $("#uploadList").append(tr);
                form.render("select", 'upload-row-' + index);

                //文件表格selector选择
                form.on('select(upload-row-selector-' + index+ ')', (data) => {
                    //console.log('data', data)
                    // console.log(data.elem); //得到select原始DOM对象
                    // console.log(data.value); //得到被选中的值
                    // console.log(data.othis); //得到美化后的DOM对象
                    let selector = $(data.elem);
                    //console.log('selector', selector);
                    let name = $(selector).attr('name');
                    if(!name){return;}

                    //记录变更数据
                    this.formData(name, data.value);
                });

                return tr;
            })();

            //替换
            this.replace = function(inputFile){
                this.file = inputFile;
                let tds = this.tr.children();

                //更新信息
                tds.eq(0).text(inputFile.name);
                tds.eq(1).text((inputFile.size >> 10) + 'kb');

                //隐藏按钮
                tds.eq(4).find('>button').addClass('layui-hide');

                //显示删除按钮
                tds.eq(4).find('.action-delete').removeClass('layui-hide');
                //恢复默认背景
                this.tr.css('background-color', '');

                this.showErrorMsg = undefined;
                this.preparedToUpload = true;
            };

            //删除
            this.remove= function(){
                if(this._removed){return;}
                // 移除
                this.tr.remove();
                this._removed = true;
            };

            //准备好上传标志
            this.preparedToUpload = true;
            
            //准备上传
            this.beginUpload = function () {
                // 隐藏按钮
                let tds = this.tr.children().eq(4);
                let buttons = tds.find('>button');
                buttons.addClass('layui-hide');

                //添加load动画
                let loading = tds.find('>i');
                loading.removeClass('layui-hide').addClass('layui-anim layui-anim-rotate layui-anim-loop');
            };
            //结束上传
            this.endUpload = function (res) {
                this.preparedToUpload = false;
                //解析错误
                let buttons = this.tr.children().eq(4);
                // console.log(res);

                if(res.code == ERROR_CODE.SUCCESS){
                    //上传成功
                    buttons.html('<i class="layui-icon layui-icon-ok" style="font-size: 30px; color: #5FB878;"></i><span style="color: #5FB878;">ok</span>')
                }else{
                    //移除load动画
                    buttons.find('>i').addClass('layui-hide').removeClass('layui-anim layui-anim-rotate layui-anim-loop');

                    //显示所有操作
                    buttons.find('>button').removeClass('layui-hide');

                    //错误消息弹窗
                    if(res.code < 0){
                        this.showErrorMsg = function () {
                            layer.open({
                                title: ['请求错误-' + res.status,'color: #1E9FFF;'],
                                content: res.responseText,
                                icon: 7
                            });
                        }
                    }else{
                        this.showErrorMsg = function () {
                            layer.open({
                                title: [['错误代码', res.code, res.msg].join('-'),'color: #1E9FFF;'],
                                content: res.data? [res.data.code, res.data.msg].join('\n'): '未知的错误',
                                icon: 7
                            });
                        }
                    }
                    //错误背景
                    this.tr.css('background-color', '#ffb0b0');
                }
            }

        };
        /**
         * 设置表单数据
         * @param key
         * @param value
         * @return {any}
         */
        File.prototype.formData = function(key, value){
            if(!this._formData){ this._formData = {};}
            if(key == undefined){
                return this._formData;
            }
            if (value == undefined){
                return this._formData[key];
            }
            this._formData[key] = value;
        };
        File.Index = {};
        File._list = [];
        File.size = function(){
            return this._list.length;
        };
        /**
         * 读取指定file
         * @param {number} i
         * @return {file}
         */
        File.get = function(i){
            return this._list[i];
        };
        File.getAll = function(){return this._list;};
        File.isDuplicate = function(inputFile){
            for(let i in this._list){
                let file = this._list[i].file;
                if(file.name == inputFile.name && file.lastModified == inputFile.lastModified && file.size == inputFile.size){
                    return true;
                }
            }
            return false;
        };
        File.from = function(inputFile){
          let file = new File(inputFile);
          this._list.push(file);
          return file;
        };
        File.replace = function(file, inputFile){
            file.replace(inputFile);
        };
        File.remove = function(file){
            file.remove();
            for(let i in this._list){
                if(file == this._list[i]){
                    this._list.splice(i, 1);
                    break;
                }
            }
        };

        //用户选择文件上传
        //监听拖动区域
        $('#upload_area').on('drop', function (e) {
            e.preventDefault();
            console.log(e);
            e.preventDefault();
            let files = e.dataTransfer.files; //获取要上传的文件对象(可以上传多个)
            console.log(files)
        }).on('click', function (e) {
            e.stopPropagation();
            $('#input-upload').click();
        });
        //文件输入框点击
        $('#input-upload').on('change', function (e) {
            e.stopPropagation();
            let inputFiles = e.currentTarget.files;
            // console.log('inputFiles', inputFiles);
            $(this).attr('multiple', true);
            if(inputFiles.length == 0){
                $(this).data('reselect', undefined); //取消重新选择
                return;
            }
            // console.log('文件输入', this);
            let file = $(this).data('reselect');
            $(this).data('reselect', undefined); //取消重新选择
            //检查是否为重选替换
            if(file){
                //替换文件
                // console.log('替换文件为', inputFiles[0]);
                if(File.isDuplicate(inputFiles[0])){layer.msg('选择了重复文件', {icon: 5, time: 2000}); return;} //重复
                File.replace(file, inputFiles[0]);
                return;
            }
            //正常选择文件
            let cnt = 0;
            for(let i=0; i< inputFiles.length; i++){
                if(File.isDuplicate(inputFiles[i])){console.log('重复');continue;}
                File.from(inputFiles[i]);
                cnt++;
                if(File.size() >= 24){
                    layer.msg('选择了太多文件!', {icon: 5, time: 2000});
                    break;
                }
            }
            if(cnt == 0){
                layer.msg('选择了重复文件', {icon: 5, time: 2000});
            }else{
                window.resizeWindowHeight?window.resizeWindowHeight():'';
            }

        });

        //文件上传
        let Pointer = 0;
        function uploadFile(file, continueUpload){
            if(!file){
                if(File.size() == 0){return;}
                let files = File.getAll();
                while (true){
                    if(Pointer >= files.length){
                        //一轮上传结束
                        $('#uploadButton').html('开始上传').removeClass('layui-disable');
                        return;
                    }
                    file = File.get(Pointer);
                    Pointer++;
                    if(file.preparedToUpload){
                        break;
                    }
                }//找到下一个可以上传的文件
                continueUpload = true;
            }
            let msg = function(content){
                layer.msg(content, {icon: 5, time: 2000});
            };

            //校验表单数据
            let reportId = file.formData('reportId');
            if(!reportId){msg('请选择报表类型'); return;}
            let classId = file.formData('classId');
            if(!classId){msg('请选择人员类型'); return;}

            //生成表单
            let formData = new FormData();
            formData.append('reportId', reportId);
            formData.append('classId', classId);
            formData.append('file', file.file);

            //上传
            $.ajax({
                type: 'post',
                url: "/report/uploadFile",
                data: formData,
                cache: false,
                processData: false,
                contentType: false,

                success: function (res) {
                    // console.log('res', res);
                    file.endUpload(res);
                },
                error:function (res) {
                    // console.log("上传失败", res);
                    res.code = -1;
                    file.endUpload(res);
                },
                complete: function () {
                    if(continueUpload){
                        //继续上传
                        uploadFile();
                    }
                }
            });
        };

        //用户点击开始上传按钮
        $('#uploadButton').on('click', function () {
            console.log('点击上传');
            let msg = function(content){
                layer.msg(content, {icon: 5, time: 2000});
            };

            //检查表单数据完成
            if(File.size() == 0){return;}
            let files = File.getAll();
            for(let i in files){
                let file = files[i];
                if(!file.preparedToUpload){continue;}
                let reportId = file.formData('reportId');
                if(!reportId){msg('请选择报表类型'); return;}
                let classId = file.formData('classId');
                if(!classId){msg('请选择人员类型'); return;}
            }
            //进入上传状态
            for(let i in files){
                if(files[i].preparedToUpload){files[i].beginUpload();}
            }
            //开始上传
            Pointer = 0;
            uploadFile();
            $(this).html('<i class="layui-icon layui-icon-loading-1 layui-anim layui-anim-rotate layui-anim-loop"' +
                ' style="font-size: 30px; color: #9f060f;"></i>');
            $(this).addClass('layui-disable');
        });

    })
});
